package com.example.chamberlainserver.controller;

import com.example.chamberlainserver.Entry.Role;
import com.example.chamberlainserver.Service.RoleService;
import com.example.chamberlainserver.Service.UserRoleService;
import com.example.chamberlainserver.Vo.Response.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 角色管理控制器
 */
@RestController
@RequestMapping("/roles")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserRoleService userRoleService;

    /**
     * 获取所有角色
     */
    @GetMapping
    public ResponseEntity<ApiResponse<List<Role>>> getAllRoles() {
        try {
            List<Role> roles = roleService.getAllRoles();
            return ResponseEntity.ok(new ApiResponse<>(200, "获取角色列表成功", roles));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(500, "获取角色列表失败: " + e.getMessage(), null));
        }
    }

    /**
     * 根据ID获取角色
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ApiResponse<Role>> getRoleById(@PathVariable Integer id) {
        try {
            Role role = roleService.getRoleById(id);
            if (role != null) {
                return ResponseEntity.ok(new ApiResponse<>(200, "获取角色成功", role));
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(new ApiResponse<>(404, "角色不存在", null));
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(500, "获取角色失败: " + e.getMessage(), null));
        }
    }

    /**
     * 添加角色
     */
    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ApiResponse<Role>> addRole(@RequestBody Role role) {
        try {
            boolean success = roleService.addRole(role);
            if (success) {
                return ResponseEntity.status(HttpStatus.CREATED)
                        .body(new ApiResponse<>(201, "添加角色成功", role));
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(new ApiResponse<>(400, "添加角色失败", null));
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(500, "添加角色失败: " + e.getMessage(), null));
        }
    }

    /**
     * 更新角色
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ApiResponse<Role>> updateRole(@PathVariable Integer id, @RequestBody Role role) {
        try {
            role.setId(id);
            boolean success = roleService.updateRole(role);
            if (success) {
                return ResponseEntity.ok(new ApiResponse<>(200, "更新角色成功", role));
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(new ApiResponse<>(400, "更新角色失败", null));
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(500, "更新角色失败: " + e.getMessage(), null));
        }
    }

    /**
     * 删除角色
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ApiResponse<Void>> deleteRole(@PathVariable Integer id) {
        try {
            boolean success = roleService.deleteRole(id);
            if (success) {
                return ResponseEntity.ok(new ApiResponse<>(200, "删除角色成功", null));
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(new ApiResponse<>(400, "删除角色失败", null));
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(500, "删除角色失败: " + e.getMessage(), null));
        }
    }

    /**
     * 获取用户的角色列表
     */
    @GetMapping("/user/{userId}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ApiResponse<List<Role>>> getRolesByUserId(@PathVariable Integer userId) {
        try {
            List<Role> roles = userRoleService.getRolesByUserId(userId);
            return ResponseEntity.ok(new ApiResponse<>(200, "获取用户角色列表成功", roles));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(500, "获取用户角色列表失败: " + e.getMessage(), null));
        }
    }

    /**
     * 为用户分配角色
     */
    @PostMapping("/user/{userId}/assign")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ApiResponse<Void>> assignRolesToUser(
            @PathVariable Integer userId,
            @RequestBody List<Integer> roleIds) {
        try {
            boolean success = userRoleService.assignRolesToUser(userId, roleIds);
            if (success) {
                return ResponseEntity.ok(new ApiResponse<>(200, "分配角色成功", null));
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(new ApiResponse<>(400, "分配角色失败", null));
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(500, "分配角色失败: " + e.getMessage(), null));
        }
    }
}